#!/usr/bin/python
# encoding=utf-8
from SshClient import SshClient
import os
import time
import threading
#import paramiko
#ssh = paramiko.SSHClient()
count=2
serverSSHs=[
	SshClient(host='10.211.55.14', port=22, username='chenxin', password='asdfasdf')
]

def init():
	cmds=[
		'sudo  wget https://repo.mysql.com//mysql-apt-config_0.8.3-1_all.deb',
		'sudo dpkg -i mysql-apt-config_0.8.3-1_all.deb',
		'sudo apt-get update',
		'sudo apt-get install mysql-server']
	for index,value in enumerate(serverSSHs):
		ret=serverSSHs[index].sexecute('ls|grep mysql|wc -l')
		res=int(ret['out'][0].replace("\n",""))
		if res<1:
			for i in range(0, len(cmds)):
				ret=value.execute(cmds[i],True)
	#备份配置文件
	for index,value in enumerate(serverSSHs):
		ret=value.execute("cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/mysql.conf.d/mysqld.cnf_back",True)

def changeConf(ser,sid):
	ser.execute("rm /etc/mysql/mysql.conf.d/mysqld.cnf",True)
	ser.execute("cp /etc/mysql/mysql.conf.d/mysqld.cnf_back /etc/mysql/mysql.conf.d/mysqld.cnf",True);
	#修改配置文件
	str=ser.sexecute('cat /etc/mysql/mysql.conf.d/mysqld.cnf')

	if len(str['out'])>0:
		for i in range(0, len(str['out'])):            
			str['out'][i]=str['out'][i].replace("127.0.0.1","0.0.0.0")
			
	str['out']+='log-bin=mysql-bin\nserver-id='+sid+'\n'
	t=ser.sexecute('sudo bash -c \'echo "%s">/etc/mysql/mysql.conf.d/mysqld.cnf\''%''.join(str['out']))
	#重启服务
	ser.execute('/etc/init.d/mysql restart',True)

def m2s():
	#判断mysql是否启动成功
	lastPid=serverSSHs[0].execute('pgrep mysqld')
	if len(lastPid['out']) < 2:
	   timer = threading.Timer(5,m2s)
	   timer.start()
	else:
		serverSSHs[0].sexecute('mysql -uroot -pasdfasdf -e "use mysql; GRANT REPLICATION SLAVE ON *.* to \\"mysync\\"@\\"%\\" identified by \\"q123456\\";" ')
		t= serverSSHs[0].sexecute('mysql -uroot -pasdfasdf -e "show master status;" ')
		info= t['out'][1].split( )
		s_mysqlbin = info[0]
		s_position = info[1]
		for index,value in enumerate(serverSSHs):
			if index !=0:
				value.sexecute('mysql -uroot -pasdfasdf -e "use mysql; update user set host = \\"%\\" where user =\\"root\\";  flush privileges; " ')
				value.sexecute('mysql -uroot -pasdfasdf -e "use mysql; change master to master_host=\\"'+server1 +'\\",master_user=\\"mysync\\",master_password=\\"q123456\\",master_log_file=\\"'+s_mysqlbin + '\\",master_log_pos='+s_position+'; " ')
				value.sexecute('mysql -uroot -pasdfasdf -e "start slave;"')


if __name__ == '__main__':   
	for index,value in enumerate(serverSSHs):
		index=index+1
		changeConf(value,str(index))
	m2s()
	print "end"